package com.musifind.activities;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.musifind.common.GeneralHelper;
import com.musifind.musicplayer.SongsManager;
import com.musifind.utils.FavouritesDatabase;
import com.musifind.utils.PlayerUtils;
import com.musifind.utils.SessionManager;
import com.musifind.wsclient.service.ListeningService;
import com.squareup.picasso.Picasso;

public class MusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private ImageView imgCover;
	private ToggleButton tglFavourite;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();
	private SongsManager songManager;
	private PlayerUtils utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;

	FavouritesDatabase favDB;
	String trackId;
	String trackURL = "";
	String trackName = "";
	String artistName = "";
	String albumName = "";
	String albumYear = "";
	String coverImage = "";

	private int i = 0;

	SessionManager session;

	// private ArrayList<HashMap<String, String>> songsList = new
	// ArrayList<HashMap<String, String>>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		session = new SessionManager(getApplicationContext());

		// activity starts as push old activity to left
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

		favDB = new FavouritesDatabase(MusicPlayerActivity.this);

		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnForward = (ImageButton) findViewById(R.id.btnForward);
		btnBackward = (ImageButton) findViewById(R.id.btnBackward);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		imgCover = (ImageView) findViewById(R.id.imgNowListening);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songTitleLabel = (TextView) findViewById(R.id.songTitle);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
		tglFavourite = (ToggleButton) findViewById(R.id.tglFavourite);

		btnPlaylist.setVisibility(View.INVISIBLE);

		// Mediaplayer
		mp = new MediaPlayer();
		songManager = new SongsManager();
		utils = new PlayerUtils();

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important
		mp.setOnCompletionListener(this); // Important

		// // Getting all songs list
		// //songsList = songManager.getPlayList();
		//

		// if song already saved as favourite, the star toggle will come as checked, else not
		isFavourite();
		// // By default play first song
		playSong(0);

		btnPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// check for already playing
				if (mp.isPlaying()) {
					if (mp != null) {
						mp.pause();
						btnPlay.setImageResource(R.drawable.btn_play);
					}
				} else {
					// Resume song
					if (mp != null) {
						mp.start();
						btnPlay.setImageResource(R.drawable.btn_pause);
					}
				}
			}
		});

		btnForward.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				if (currentPosition + seekForwardTime <= mp.getDuration()) {
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				} else {
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});

		btnBackward.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int currentPosition = mp.getCurrentPosition();
				if (currentPosition - seekBackwardTime >= 0) {
					mp.seekTo(currentPosition - seekBackwardTime);
				} else {
					mp.seekTo(0);
				}
			}
		});

		btnNext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				i++;
				playSong(currentSongIndex);
				// check if next song is there or not
				// if (currentSongIndex < (songsList.size() - 1)) {
				// playSong(currentSongIndex + 1);
				// currentSongIndex = currentSongIndex + 1;
				// } else {
				// // play first song
				// playSong(0);
				// currentSongIndex = 0;
				// }
			}
		});

		btnPrevious.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				i--;
				playSong(currentSongIndex);

				// if (currentSongIndex > 0) {
				// playSong(currentSongIndex - 1);
				// currentSongIndex = currentSongIndex - 1;
				// } else {
				// // play last song
				// playSong(songsList.size() - 1);
				// currentSongIndex = songsList.size() - 1;
				// }
			}
		});

		btnRepeat.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (isRepeat) {
					isRepeat = false;
					GeneralHelper.showPurpleToast(getApplicationContext(), "Tekrar açık");
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				} else {
					isRepeat = true;
					GeneralHelper.showPurpleToast(getApplicationContext(), "Tekrar kapalı");
					isShuffle = false;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});

		btnShuffle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (isShuffle) {
					isShuffle = false;
					GeneralHelper.showPurpleToast(getApplicationContext(), "Karışık Mod kapalı");
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				} else {
					isShuffle = true;
					GeneralHelper.showPurpleToast(getApplicationContext(), "Karışık Mod açık");
					isRepeat = false;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});

		btnPlaylist.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
				startActivityForResult(i, 100);
			}
		});

		tglFavourite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					favDB.saveFavourite(trackId, trackURL, coverImage, trackName, artistName, albumName);
					GeneralHelper.showBlueToast(getApplicationContext(), "Şarkı favorilerinize eklendi");

				} else {
					favDB.deleteFavourite(trackId);
					GeneralHelper.showRedToast(getApplicationContext(), "Şarkı favorilerinizden çıkarıldı");
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 100) {
			currentSongIndex = data.getExtras().getInt("songIndex");
			// play selected song
			playSong(currentSongIndex);
		}

	}

	public void playSong(int songIndex) {
		// Play song
		try {
			// buraya live userın dinlediği şarkı kaydı atılacak

			// Sample sample = new Sample();
			// Track tracks = sample.getTracks();
			// String trackURL = tracks.getSecure_url();

			// --------------

			// FizyControllers controllers = new FizyControllers();
			// Search search = controllers.search("good");
			// // ekrana trackları basmak icin
			// // System.out.println("::TRACK::");
			// for (Track track : search.getTracks()) {
			// Log.i("track body: ", track.getBody());
			// Log.i("track name: ", track.getName());
			// }
			// //ekrana album larÄ± basmak icin
			// System.out.println("::ALBUM::");
			// for (Album album : search.getAlbums()) {
			// System.out.println("name :" + album.getName());
			// System.out.println("cover large image :" +
			// album.getCover_large());
			// }
			// //ekrana artist larÄ± basmak icin
			// System.out.println("::ARTIST::");
			// for (Artist artist : search.getArtists()) {
			// System.out.println("name :" + artist.getName());
			// System.out.println("birth date :" + artist.getBirth_date());
			// }
			//
			// //ekrana mood larÄ± basmak icin
			// System.out.println("::MOOD::");
			// for (Mood mood : search.getMoods()) {
			// System.out.println("title :" + mood.getTitle());
			// System.out.println("emotions :" + mood.getEmotions());
			// }

			// secilen 3. track bilgilerini gostermek icin //track.get ile ws
			// den donem daha fazla bilgiye ulasabilirsin

			// Track2 track = controllers.getTrack(search.getTracks().get(i).getId() + "");
			//
			// // System.out.println("name :" + track.getName());
			// String releaseDate = track.getAlbum().getRelease_date();
			if (albumYear != null) {
				songTitleLabel.setText(artistName + " - " + trackName + "\n" + albumName + " (" + albumYear + ")");
			} else {
				songTitleLabel.setText(artistName + " - " + trackName + "\n" + albumName);
			}
			// Log.d("Album Image URL", String.valueOf(track.getAlbum().getCover_medium()));
			// String cover_url = track.getAlbum().getCover_large();

			// Trigger the download of the URL asynchronously into the image view.
			Picasso.with(MusicPlayerActivity.this).load(coverImage).into(imgCover);

			// Bitmap bitmapCover = GeneralHelper.getBitmapFromURL(coverImage);
			// imgCover.setImageBitmap(bitmapCover);
			// System.out.println("url :" + track.getSecure_url());
			// String trackURL = track.getSecure_url();
			// ----------
			mp.reset();
			// mp.setDataSource(songsList.get(songIndex).get("songPath"));
			mp.setDataSource(trackURL);
			mp.prepare();
			mp.start();
			// Displaying Song title
			// String songTitle = songsList.get(songIndex).get("songTitle");
			// songTitleLabel.setText(songTitle);

			btnPlay.setImageResource(R.drawable.btn_pause);

			// setting progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateProgressBar() {
		mHandler.postDelayed(mUpdateTimeTask, 100);
	}

	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			try {
				long totalDuration = mp.getDuration();
				long currentDuration = mp.getCurrentPosition();

				// Displaying Total Duration time
				songTotalDurationLabel.setText("" + utils.milliSecondsToTimer(totalDuration));
				// Displaying time completed playing
				songCurrentDurationLabel.setText("" + utils.milliSecondsToTimer(currentDuration));

				// Updating progress bar
				int progress = (int) (utils.getProgressPercentage(currentDuration, totalDuration));
				// Log.d("Progress", ""+progress);
				songProgressBar.setProgress(progress);

				// Running this thread after 100 milliseconds
				mHandler.postDelayed(this, 100);
			} catch (Exception e) {
			}
		}
	};

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		// şarkının bitimi burada dinlenecek
		ListeningService listeningService = new ListeningService();
		listeningService.stopListening(session.getUserId());
		i++;
		// playSong(currentSongIndex);
		// check for repeat is ON or OFF
		// if (isRepeat) {
		// // repeat is on play same song again
		// playSong(currentSongIndex);
		// }
		// else if (isShuffle) {
		// // shuffle is on - play a random song
		// Random rand = new Random();
		// currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
		// playSong(currentSongIndex);
		// } else {
		// // no repeat or shuffle ON - play next song
		// if (currentSongIndex < (songsList.size() - 1)) {
		// playSong(currentSongIndex + 1);
		// currentSongIndex = currentSongIndex + 1;
		// } else {
		// // play first song
		// playSong(0);
		// currentSongIndex = 0;
		// }
		// }
	}

	public void bundleDatas() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			trackId = bundle.getString("track_id");
			trackURL = (String) bundle.get("track_url");
			trackName = (String) bundle.get("track_name");
			artistName = (String) bundle.get("artist_name");
			albumName = (String) bundle.get("album_name");
			albumYear = (String) bundle.get("album_year");
			coverImage = (String) bundle.get("cover_image");

			ListeningService listeningService = new ListeningService();
			listeningService.createListening(session.getUserId(), trackId, trackName, artistName, coverImage);
		}
	}

	public void isFavourite() {
		bundleDatas();
		// if song already saved as favourite, the star toggle will come as checked, else not
		tglFavourite.setChecked(favDB.isFavourite(trackId));
	}

	@Override
	public void onDestroy() {
		// Media playerın kapandığı burada dinleniyor. buraya da offline kaydı atılmalı
		ListeningService listeningService = new ListeningService();
		listeningService.stopListening(session.getUserId());
		super.onDestroy();
		mp.release();
	}
}